#!/usr/bin/env php
<?php
/*
 * n98-magerun.phar historical left-over stub. Informs that this is not the file and automatically downloads latest
 * stable version and replaces itself with it.
 */

echo "Info: Magerun has not been downloaded yet, downloading it ...\n";

$url = 'https://files.magerun.net/n98-magerun.phar';
$target = 'n98-magerun.phar';

$old = md5_file($target);
$file = @fopen($url, 'r');
if ($file === false) {
    fputs(STDERR, "Error downloading magerun phar file\n");
    fputs(STDERR, "Please install manually from '$url'\n");
    exit(1);
}
$result = @file_put_contents($target, $file);
if (false === $result) {
    fputs(STDERR, "Error downloading magerun phar file\n");
    fputs(STDERR, "Failed to write '$url' to '$target'\n");
    fputs(STDERR, "Please install manually\n");
    exit(1);
}
if ($old === md5_file($target)) {
    fputs(STDERR, "Error downloading magerun phar file\n");
    fputs(STDERR, "File is of same content\n");
    fputs(STDERR, "Please install manually\n");
    exit(1);
}

echo "Info: Download done, executing it with original parameters ...\n";

$args = implode(' ', array_map('escapeshellarg', array_slice($argv, 1)));
passthru(sprintf('%s -f %s -- %s', escapeshellarg(PHP_BINARY), escapeshellarg($target), $args), $status);
if (0 !== $status) {
    fputs(STDERR, "Error executing downloaded phar file\n");
}
exit($status);
